package com.db.com.db.transport;

import com.db.domain.Cache;
import com.db.domain.Observer;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

class FileTransport implements Transportable {
    private List<Observer> observerList;
    private Cache cache;
    private File file;

    FileTransport(File file) {
        this.file = file;
    }

    @Override
    public void addObserver(Observer o) {
        observerList.add(o);
    }

    @Override
    public boolean removeObserver(Observer o) {
        return observerList.remove(o);
    }

    @Override
    public void notifyObservers() {
        for (Observer o : observerList) {
            o.updateCache(cache);
        }
    }

    @Override
    public void updateCache(Cache cache) {
        this.cache = cache;
        saveCache(cache);
        notifyObservers();
    }

    @Override
    public void saveCache(Cache cache) {
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file);
            fileWriter.append(cache.toString());
            fileWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
